package org.jeecg.modules.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysEmployee;
import org.jeecg.modules.system.service.ISysEmployeeService;
import org.jeecg.modules.wms.entity.WmsRequisition;
import org.jeecg.modules.wms.entity.WmsRequisitionAccessory;
import org.jeecg.modules.wms.entity.WmsRequisitionProfile;
import org.jeecg.modules.wms.service.IWmsRequisitionService;
import org.jeecg.modules.wms.vo.WmsRequisitionApproveVO;
import org.jeecg.modules.wms.vo.WmsRequisitionExecuteVO;
import org.jeecg.modules.wms.vo.WmsRequisitionRejectVO;
import org.jeecg.modules.wms.vo.WmsRequisitionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 领料单管理
 */
@Slf4j
@Api(tags = "领料单管理")
@RestController
@RequestMapping("/wms/requisition")
public class WmsRequisitionController extends JeecgController<WmsRequisition, IWmsRequisitionService> {

    @Autowired
    private IWmsRequisitionService wmsRequisitionService;
    
    @Autowired
    private ISysEmployeeService employeeService;

    /**玻外胶条
     * 分页列表查询
     */
    @AutoLog(value = "领料单管理-分页列表查询")
    @ApiOperation(value = "领料单管理-分页列表查询", notes = "领料单管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmsRequisition>> queryPageList(WmsRequisition wmsRequisition,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        // 创建分页对象
        Page<WmsRequisition> page = new Page<>(pageNo, pageSize);
        
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        
        // 添加查询条件
        params.put("requisitionNo", req.getParameter("requisitionNo_like"));
        params.put("orderNo", req.getParameter("orderNo_like"));
        params.put("status", req.getParameter("status"));
        params.put("pickingStatus", req.getParameter("pickingStatus"));
        params.put("beginRequisitionDate", req.getParameter("beginRequisitionDate"));
        params.put("endRequisitionDate", req.getParameter("endRequisitionDate"));
        params.put("beginApproveDate", req.getParameter("beginApproveDate"));
        params.put("endApproveDate", req.getParameter("endApproveDate"));
        params.put("approverName", req.getParameter("approverName"));
        if(oConvertUtils.isNotEmpty(req.getParameter("approver"))){
            //根据员工id获取username
            SysEmployee employee = employeeService.getById(req.getParameter("approver"));
            if(employee != null){
                params.put("approver", employee.getUsername());
            }
        }
        params.put("requisitionPerson", req.getParameter("requisitionPerson"));
        params.put("optimizationSoftwareType", req.getParameter("optimizationSoftwareType"));
        
        // 调用Service查询
        IPage<WmsRequisition> pageList = wmsRequisitionService.queryPageList(page, params);
        
        return Result.OK(pageList);
    }

    /**
     * 添加
     */
    @AutoLog(value = "领料单管理-添加")
    @ApiOperation(value = "领料单管理-添加", notes = "领料单管理-添加")
    @PostMapping(value = "/add")
    public Result<WmsRequisition> add(@RequestBody WmsRequisitionVO wmsRequisitionVO) {
        return wmsRequisitionService.saveRequisition(wmsRequisitionVO);
    }

    /**
     * 编辑
     */
    @AutoLog(value = "领料单管理-编辑")
    @ApiOperation(value = "领料单管理-编辑", notes = "领料单管理-编辑")
    @PostMapping(value = "/edit")
    public Result<WmsRequisition> edit(@RequestBody WmsRequisitionVO wmsRequisitionVO) {
        return wmsRequisitionService.updateRequisition(wmsRequisitionVO);
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "领料单管理-通过id删除")
    @ApiOperation(value = "领料单管理-通过id删除", notes = "领料单管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        boolean success = wmsRequisitionService.removeRequisitionById(id);
        if (success) {
            return Result.OK("删除成功!");
        } else {
            return Result.error("删除失败，只能删除待审核状态的领料单!");
        }
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "领料单管理-批量删除")
    @ApiOperation(value = "领料单管理-批量删除", notes = "领料单管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        boolean success = wmsRequisitionService.removeRequisitionByIds(idList);
        if (success) {
            return Result.OK("批量删除成功!");
        } else {
            return Result.error("批量删除失败，只能删除待审核状态的领料单!");
        }
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "领料单-通过id查询")
    @ApiOperation(value = "领料单-通过id查询", notes = "领料单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmsRequisitionVO> queryById(@RequestParam(name = "id", required = true) String id) {
        WmsRequisitionVO wmsRequisition = wmsRequisitionService.getRequisitionById(id);
        if (wmsRequisition == null) {
            return Result.error("未找到对应数据");
        }
        
        // 获取审核人姓名
        if (StringUtils.isNotBlank(wmsRequisition.getApprover())) {
            QueryWrapper<SysEmployee> employeeQueryWrapper = new QueryWrapper<>();
            employeeQueryWrapper.eq("username", wmsRequisition.getApprover());
            SysEmployee employee = employeeService.getOne(employeeQueryWrapper);
            if (employee != null) {
                wmsRequisition.setApproverName(employee.getEmpName());
            }
        }
        
        return Result.OK(wmsRequisition);
    }

    /**
     * 查询型材明细列表
     */
    @AutoLog(value = "领料单管理-查询型材明细列表")
    @ApiOperation(value = "领料单管理-查询型材明细列表", notes = "领料单管理-查询型材明细列表")
    @GetMapping(value = "/getProfileList/{requisitionId}")
    public Result<List<WmsRequisitionProfile>> getProfileList(@PathVariable(name = "requisitionId") String requisitionId) {
        List<WmsRequisitionProfile> profileList = wmsRequisitionService.getProfileList(requisitionId);
        return Result.OK(profileList);
    }

    /**
     * 查询配件明细列表
     */
    @AutoLog(value = "领料单管理-查询配件明细列表")
    @ApiOperation(value = "领料单管理-查询配件明细列表", notes = "领料单管理-查询配件明细列表")
    @GetMapping(value = "/getAccessoryList/{requisitionId}")
    public Result<List<WmsRequisitionAccessory>> getAccessoryList(@PathVariable(name = "requisitionId") String requisitionId) {
        List<WmsRequisitionAccessory> accessoryList = wmsRequisitionService.getAccessoryList(requisitionId);
        return Result.OK(accessoryList);
    }

    /**
     * 提交审核
     */
    @AutoLog(value = "领料单管理-提交审核")
    @ApiOperation(value = "领料单管理-提交审核", notes = "领料单管理-提交审核")
    @PostMapping(value = "/submit")
    public Result<?> submit(@RequestBody Map<String, Object> params) {
        String id = (String) params.get("id");
        if (id == null) {
            return Result.error("领料单ID不能为空");
        }
        return wmsRequisitionService.submitRequisition(id);
    }

    /**
     * 审核通过
     */
    @AutoLog(value = "领料单管理-审核通过")
    @ApiOperation(value = "领料单管理-审核通过", notes = "领料单管理-审核通过")
    @PostMapping(value = "/approve")
    public Result<?> approve(@RequestBody WmsRequisitionApproveVO approveVO) {
        if (approveVO.getId() == null) {
            return Result.error("领料单ID不能为空");
        }

        // 获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        approveVO.setApprover(username);

        // 处理审核信息，包括附件
        return wmsRequisitionService.approveRequisition(approveVO.getId(), approveVO.getApprover(), approveVO.getApproveComment(), approveVO.getAttachments());
    }

    /**
     * 审核驳回
     */
    @AutoLog(value = "领料单管理-审核驳回")
    @ApiOperation(value = "领料单管理-审核驳回", notes = "领料单管理-审核驳回")
    @PostMapping(value = "/reject")
    public Result<?> reject(@RequestBody WmsRequisitionRejectVO rejectVO) {
        if (rejectVO.getId() == null) {
            return Result.error("领料单ID不能为空");
        }
        if (rejectVO.getApproveComment() == null || rejectVO.getApproveComment().trim().isEmpty()) {
            return Result.error("驳回意见不能为空");
        }

        // 获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        rejectVO.setApprover(username);

        return wmsRequisitionService.rejectRequisition(rejectVO.getId(), rejectVO.getApprover(), rejectVO.getApproveComment());
    }

    /**
     * 执行领料
     */
    @AutoLog(value = "领料单管理-执行领料")
    @ApiOperation(value = "领料单管理-执行领料", notes = "领料单管理-执行领料")
    @PostMapping(value = "/executeRequisition")
    public Result<?> executeRequisition(@RequestBody WmsRequisitionExecuteVO executeVO) {
        return wmsRequisitionService.executeRequisition(executeVO);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmsRequisition wmsRequisition) {
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        
        // 添加查询条件
        params.put("requisitionNo", request.getParameter("requisitionNo_like"));
        params.put("orderNo", request.getParameter("orderNo_like"));
        params.put("status", request.getParameter("status"));
        params.put("pickingStatus", request.getParameter("pickingStatus"));
        params.put("beginRequisitionDate", request.getParameter("beginRequisitionDate"));
        params.put("endRequisitionDate", request.getParameter("endRequisitionDate"));
        params.put("beginApproveDate", request.getParameter("beginApproveDate"));
        params.put("endApproveDate", request.getParameter("endApproveDate"));
        params.put("approverName", request.getParameter("approverName"));
        if(oConvertUtils.isNotEmpty(request.getParameter("approver"))){
            //根据员工id获取username
            SysEmployee employee = employeeService.getById(request.getParameter("approver"));
            if(employee != null){
                params.put("approver", employee.getUsername());
            }
        }
        params.put("requisitionPerson", request.getParameter("requisitionPerson"));
        params.put("optimizationSoftwareType", request.getParameter("optimizationSoftwareType"));
        
        // 调用Service查询
        List<WmsRequisition> list = wmsRequisitionService.queryExportList(params);

        return super.exportXlsByResult(request, WmsRequisition.class, "领料单管理", list);
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();
            return wmsRequisitionService.importExcel(file, request);
        }
        return Result.error("上传文件为空！");
    }

    /**
     * 根据订单编号查询可用于领料的领料单列表
     * 条件：已审核(status=1)且未全部领料(picking_status=0或1)的领料单
     */
    @AutoLog(value = "领料单管理-根据订单编号查询可用领料单")
    @ApiOperation(value = "领料单管理-根据订单编号查询可用领料单", notes = "查询已审核且未全部领料的领料单")
    @GetMapping(value = "/listByOrderNo")
    public Result<List<WmsRequisition>> listByOrderNo(@RequestParam(name = "orderNo", required = true) String orderNo) {
        if (StringUtils.isBlank(orderNo)) {
            return Result.error("订单编号不能为空");
        }
        
        // 构建查询条件
        QueryWrapper<WmsRequisition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        queryWrapper.eq("status", "1"); // 已审核
        queryWrapper.in("picking_status", Arrays.asList("0", "1")); // 未领料或部分领料
        queryWrapper.orderByDesc("create_time"); // 按创建时间倒序
        
        List<WmsRequisition> requisitionList = wmsRequisitionService.list(queryWrapper);
        
        return Result.OK(requisitionList);
    }
} 